package com.wc.算法提高课.A第一章_动态规划.最长上升子序列模型.导弹防御系统;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/5/7 21:10
 * @description https://www.acwing.com/problem/content/189/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 55;
    static int[] q = new int[N], up = new int[N], down = new int[N];
    static int n, res;

    public static void main(String[] args) {
        while (true) {
            n = sc.nextInt();
            if (n == 0) break;
            for (int i = 1; i <= n; i++) q[i] = sc.nextInt();
            res = n;
            dfs(1, 0, 0);
            out.println(res);
        }
        out.flush();
    }

    static void dfs(int u, int su, int sd) {
        if (su + sd >= res) return;
        if (u == n + 1) {
            res = su + sd;
            return;
        }
        // 放到上升子序列当中
        int k = 1;
        while (k <= su && up[k] >= q[u]) k++;
        int t = up[k];
        up[k] = q[u];
        if (k <= su) dfs(u + 1, su, sd);
        else dfs(u + 1, su + 1, sd);
        up[k] = t;
        // 放到下降子序列
        k = 1;
        while (k <= sd && down[k] <= q[u]) k++;
        t = down[k];
        down[k] = q[u];
        if (k <= sd) dfs(u + 1, su, sd);
        else dfs(u + 1, su, sd + 1);
        down[k] = t;
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}